<template>
  <div class="count">
    <van-popup :close-on-click-overlay="false" v-model:show="showEmitName" :style="{ padding: '34px 14px',}"   >
      <div style="margin-top: 4px;text-align: center;font-size: 14px;color: #262827;">给自己设置个有趣的名字吧</div>
      <div style="margin-top: 4px;text-align: center;font-size: 14px;color: #262827;"> 然后再开始聊天吧~</div>
      <van-cell-group inset style="width: 280px;margin:10px 0;background-color: #C6C6C6">
        <van-field :maxlength="8" style="background-color: #C6C6C6;color: #747474;" class="emit_name" v-model="wy_name" label="" placeholder="请输入名字" />
      </van-cell-group>
      <div style="margin-top: 4px;text-align: left;font-size: 14px;color: #939393;">中文字、数字、字母、不超过8个字</div>
      <div style="margin-top: 4px;text-align: left;font-size: 14px;color: #939393;">设置后无法修改</div>
      <div style="display:flex;justify-content: center;margin-top: 10px;">
        <div @click="updateUser" style="background-color: #1A674E;color: #fff;border-radius: 8px;width: 118px;height: 38px;line-height: 38px;text-align: center">确定</div>
      </div>
<!--      <div style="text-align: center;width:200px">因发布违规内容</div>-->
<!--      <div style="text-align: center">已被永久禁言</div>-->
      <div @click="showEmitName = false" style="position: absolute;right: 10px;top: 10px;">
        <van-image
            width="30"
            height="30"
            :src="greenClose"
        />
      </div>
    </van-popup>
    <van-popup v-model:show="showLiL" :style="{ padding: '34px 64px',}" round  >
      <div style="text-align: center;width:200px">因发布违规内容</div>
      <div style="text-align: center">已被永久禁言</div>
      <div @click="showLiL = false" style="position: absolute;right: 10px;top: 10px;">
        <van-image
            width="30"
            height="30"
            :src="greenClose"
        />
      </div>
    </van-popup>
    <van-popup v-model:show="showLiY" :style="{ padding: '34px 64px',}"  round>
      <div style="text-align: center;width:200px">因发布违规内容</div>
      <div style="text-align: center">已被禁言2小时</div>
      <div @click="showLiY = false" style="position: absolute;right: 10px;top: 10px;">
        <van-image
            width="30"
            height="30"
            :src="greenClose"
        />
      </div>

    </van-popup>

    <div id="top-lo" class="count_count" style="padding-bottom: 10px">
      <div style="white-space: pre-wrap; " v-for="(item,key) in count" :key="key">
        {{item}}
        <!--        <van-highlight :source-string="'请认准蛇货协议球推介平台智博体育，已验证靠谱稳定秒出款 单场投注请勿超过5W 反常注单会引起平台注意 点击下方链接进入 智博体育1919，\\n官方投注入口>>'" />-->
        <!--        <p style="white-space: pre-wrap; "> 请认准蛇货协议球推介平台智博体育，已验证靠谱稳定秒出款 单场投注请勿超过5W 反常注单会引起平台注意 点击下方链接进入 智博体育1919，\n官方投注入口>></p>-->

      </div>
      <!--      <div>请认准蛇货协议球推介平台</div>-->
      <!--      <div>智博体育，已验证靠谱稳定秒出款</div>-->
      <!--      <div>单场投注请勿超过5W</div>-->
      <!--      <div>反常注单会引起平台注意</div>-->
      <!--      <div>点击下方链接进入</div>-->
      <!--      <div>智博体育1919，官方投注入口>></div>-->
    </div>
    <!--    <div id="top-li" style="padding: 11px;padding-bottom: 0" @click="openUrl">-->
    <!--      <n-carousel>-->
    <!--        <img-->
    <!--            class="carousel-img"-->
    <!--            :src="banner"-->
    <!--        >-->
    <!--      </n-carousel>-->
    <!--    </div>-->
    <div class="count_chat_box" :style="{height:+getViewPortW-3+'px'}">
      <!--      <div style="height: 50px;line-height: 46px;font-size: 16px;color: #48D9AA;font-weight: bold; padding-left: 16px">-->
      <!--        <div style="position: relative;display: inline-block">聊天-->
      <!--          <div class="line-lt"></div>-->
      <!--        </div>-->

      <!--      </div>-->
      <van-notice-bar
          color="#fff" background="#4B4B4B"
          left-icon="volume-o"
          :text="vlaueHead"
          style="font-size: 13px;"
      >
        <template v-slot:left-icon>
          <van-image
              width="16px"
              height="16px"
              fit="contain"
              :src="gonggao"
          />
        </template>
        <!--        <div #left-icon>11</div>-->
      </van-notice-bar>
      <div class="chat_wapper" :style="{height:(+getViewPortW-94)+'px'}">

        <!--        <van-pull-refresh v-model="refreshing" @refresh="onrefresh">-->

        <div :style="{height:(getViewPortW-94)+'px'}" style="overflow-x:auto;padding:0 10px 5px;font-size: 14px;" id="listType">
          <ul v-for="(item,index) in list1" :key="index" :id="item.idClient">
            <li style="color:#259271" v-if="item.type!=='image'">
              <div style="padding: 4px;">
                <div style="display: inline-block;">
                  <!-- <span v-if="+item.custom.isVip===1" class="imgVipzhen" style="color: #fff;background-color: #259271;vertical-align: middle">Lv {{item.custom.isVip}}</span>
                  <span v-if="+item.custom.isVip===2" class="imgVipzhen" style="color: #fff;background-color: #E69237;vertical-align: middle">Lv {{item.custom.isVip}}</span> -->
                  <img v-if="+item.custom.isVip===1"  src="@/assets/Frame 25@2x.png" class="imgVipzhenImg" alt="">
                  <img v-if="+item.custom.isVip===2"  src="@/assets/Frame 26@2x.png" class="imgVipzhenImg" alt="">

                  <span style="display: inline-block;margin-left:6px;vertical-align: middle;">{{item.custom.username==='古德温救我'?item.custom.username:item.fromNick}}：</span>
                </div>
                <div style="color: #fff;flex:1; word-break: break-all;display: inline;vertical-align: middle;">{{item.content}}</div>
              </div>
            </li>
            <li style="color: #259271" v-else>
              <div style="padding: 4px;margin-top: 8px;display: flex;align-items:start;">
                <div style="display: flex;align-items: center;">
                  <!-- <span v-if="item.custom&&+item.custom.isVip===1" class="imgVipzhen" style="color: #fff;background-color: #259271">Lv {{item.custom.isVip}}</span>
                  <span v-if="item.custom&&+item.custom.isVip===2" class="imgVipzhen" style="color: #fff;background-color: #E69237">Lv {{item.custom.isVip}}</span> -->
                  <img v-if="+item.custom.isVip===1"  src="@/assets/Frame 25@2x.png" class="imgVipzhenImg" alt="">
                  <img v-if="+item.custom.isVip===2"  src="@/assets/Frame 26@2x.png" class="imgVipzhenImg" alt="">
                  <span style="display: inline-block;margin-left:6px;vertical-align: middle;">{{item.custom.username==='古德温救我'?item.custom.username:item.fromNick}}：</span>
                </div>
                <div style="color: #fff;vertical-align: middle;">
                  <!-- <van-image
                      width="100"
                      :src="item.file.url"
                  /> -->
                  <img :src="item.file.url" alt="" class="imgTong" @click="wayimgTongOpen(item.file.url)">
                </div>
              </div>
            </li>
          </ul>
        </div>
        <!--        </van-pull-refresh>-->
        <!--        <z-paging>111111</z-paging>-->
      </div>


    </div>
    <div class="send-chat">

      <div style="min-width: 30px;display: flex;align-items: center;margin-right: 10px;position: relative" >
        <van-icon @click.stop="upLoadImage" name="add-o" style="width: 30px;height: 30px;color: #9A9A9A;font-size: 30px" />
<!--/*        <div @click.stop="upLoadImage" style="height: 100%;text-align:center;color: #fff;background-color: #1A674E;width: 90px;margin-left: 6px;display: flex;align-items: center;justify-content: center;">发送</div>*/-->
<!--        <div v-if="showModal2"  style="display: none">-->
          <input v-if="+$is_vip===2" style="width: 30px;position: absolute;left: 0;top: 8px;opacity: 0" pictype='30010003' data-role="none" name="idFile"  id = 'uploaf' type="file" ref="foreheadCir"  accept=".jpg,.png,.bmp,.jpeg,.psd" @change="customRequest">

<!--        </div>-->
      </div>
      <div style="width: 100%;border-radius: 4px;">
        <van-field style=""  v-model="inputText" label="" @input="" @focus="titl($event)" placeholder="跟大家聊聊呗" />
      </div>

      <div style="width: 27%;display: flex;" >
        <div  @click="getUserMuteTime(inputText,$event)" style="height: 100%;text-align:center;color: #fff;background-color: #1A674E;width: 90px;margin-left: 6px;display: flex;align-items: center;justify-content: center;">发送</div>


      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import  initNIM  from './yyy.js'
import {useRouter} from "vue-router";
import gonggao from '@/assets/gonggao.png'
import {UserRecommendList, ShowNotice,UserWallet,CreateUser,GetUserMuteTime,EmptyUserName,UpdateUser} from "@/api/mock";
import { ComponentInternalInstance, getCurrentInstance, onMounted,nextTick,onBeforeUnmount  } from 'vue';
import greenClose from '@/assets/greenclose.png'
// import countList from './../../components/count_list/index'
import {ref} from "vue";
import {showFailToast,showToast,showSuccessToast} from "vant";
const showEmitName =  ref(false)
const wy_name = ref('')
const userWallet1 = ()=>{

  let pa = {
    user_id:localStorage.getItem("token")
  }
  if(!pa.user_id){
    return
  }
  console.log(pa)
  UserWallet(pa).then(
      (res) => {
        if (+res.code === 200){
          // userLI.value = res.data
          // wallet.value = res.data.wallet
          proxy.$sayIs_vip(res.data.is_vip)


          // toLogin()
        }else{
          showFailToast(res.msg);

        }

      },
      err => {
        console.log(err);
        // showFailToast("请求有误");
      }
  );
}

const titl = (e)=>{

  if(showEmitName2.value){
    e.target.blur()
    showEmitName.value = true
  }
}
const updateUser = ()=>{
  if(!wy_name.value){
    showFailToast('请输入内容')
    return
  }
  if(wy_name.value==='古德温救我'){
    showFailToast('名字违规，请重新输入')
    return
  }
  const regex = /^[\u4e00-\u9fa5A-Za-z0-9]{1,8}$/;
  if(!regex.test(wy_name.value)){
    showFailToast('中文字、数字、字母、不超过8个字')
    return;
  }


  let pa = {
    wy_accid:proxy.$wy_accid,
    wy_name:wy_name.value
  }
  UpdateUser(pa).then(res=>{
    if(+res.code===200){
      showSuccessToast('修改成功')
      showEmitName.value = false
      showEmitName2.value = false
      disconnect.value = true
      NIM.disconnect()
      // this.initialization = true
      NIM = null

      // setTimeout(()=>{
      //   init()
      // },1000)

    }else{
      showFailToast(res.msg);
    }
  })
}
const disconnect = ref(false)
const emptyUserName = ()=>{
  let pa = {
    wy_accid:proxy.$wy_accid
  }
  EmptyUserName(pa).then((res)=>{

    if(!res.data){
      nextTick(()=>{
        setTimeout(()=>{
          nextTick(()=>{
            showEmitName.value = true
          })


        },800)
      })
      showEmitName2.value = true
    }
    // debugger
    // console.log( res)
  })
}
const showEmitName2 = ref(false)
const upLoadImage = ()=>{
  if(showEmitName2.value){
    showEmitName.value = true
    return;
  }
  if(+proxy.$is_vip!==2){
    // showToast('图片仅限会员可发')
    showToast({
      message: '图片仅限会员可发',
      className:'calToa'
    })
    // position: 'bottom',
    // showFailToast()
    return
  }

  GetUserMuteTime({name:proxy.$name}).then(res=>{
    if(+res.data===1){showLiL.value = true}
    else if(+res.data===2){showLiY.value = true}
    else {
      // showModal2.value = true
      nextTick(()=>{
        // document.getElementById('uploaf').click()
      })
    }
  })





}
const showModal2 = ref(false)
const showModal3 = ref(true)
const customRequest = async () => {
  await userWallet1()
  if (showModal2.value) {
    showToast({
      message: '有图片正在发送中请稍后',
      className: 'calToa'
    })
    return
  }
  if(+proxy.$is_vip!==2){
    // showToast('图片仅限会员可发')
    showToast({
      message: '图片仅限会员可发',
      className:'calToa'
    })
    // position: 'bottom',
    // showFailToast()
    return
  }
  // let input = document.createElement("input")
  // input.type = 'file'
  // console.log(input)
  // console.log('input')
  // input.files = file
  // console.log(input)
  // console.log('input')
  // bannerL.value =
  // showToast('触发')

  let inputImage = document.getElementById('uploaf')
  // var _file = document.getElementById("fileId");
  console.log(inputImage)
  console.log('inputImage')
  await GetUserMuteTime({name: proxy.$name}).then(res => {
    if (+res.data === 1) {
      showLiL.value = true
    } else if (+res.data === 2) {
      showLiY.value = true
    } else {
      showModal2.value = true
      // showModal3.value = false
      // showModal3.value = true
      let custom = JSON.stringify(
          // {userLevel:this.$jigouSDK.userInfo.job == '2'?'助理':this.$jigouSDK.userLevel.leve,color:userLevel:this.$jigouSDK.userInfo.job == '2'?'#fcb432':this.$jigouSDK.userLevel.color,Anchor:this.$jigouSDK.userInfo.job === '2'}
          {
            isVip: 2,
            username: proxy.$name
          }
      )
      // showModal2.value = false
      NIM.sendFile({
        type: 'image',
        fileInput: inputImage,
        custom: custom,
        // blob:  new Blob([file], { type: "text/plain;charset=utf-8" }),
        done: (error, file) => {
          showModal2.value = false
          // inputImage.innerHTML = inputImage.outerHTML

          console.log(error, file)
          file.custom = {
            isVip: 2,
            username: proxy.$name
          }
          list1.value.push(file)
          document.getElementById('uploaf').value = null

          nextTick(() => {
            setTimeout(() => {
              // showModal2.value = false
              let element = document.getElementById(file.idClient)

              element.scrollIntoView();
            }, 800)
            setTimeout(() => {
              let element = document.getElementById(file.idClient)

              element.scrollIntoView();
            }, 1200)


          })
        }
      })
      // showModal2.value = true
      // nextTick(()=>{
      //   document.getElementById('uploaf').click()
      // })
    }
  })


  // const formData = new FormData()
  // if (data) {
  //   Object.keys(data).forEach((key) => {
  //     formData.append(
  //       key,
  //       data[key as keyof UploadCustomRequestOptions['data']]
  //     )
  //   })
  // }
  // formData.append('file', file.file as File)
  // const response = await FeedbackUploadImage(formData)
  // if(+response.code === 200){
  //   bannerL.value = response.data
  // }

}

const monitorKeyboard = ()=>{
  //判断机型
  let u = navigator.userAgent;
  var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  var _self = this;
  //Android
  if (isAndroid) {
    //获取原窗口的高度
    var originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
    window.onresize = function() {
      //键盘弹起与隐藏都会引起窗口的高度发生变化
      var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
      if (resizeHeight - 0 < originalHeight - 0) {
        getViewPortW.value = String(+getViewPortW.value - 120)
        //当软键盘弹起，在此处操作
        //_self.show_bo = false;
      } else {
        getViewPortW.value = String(+getViewPortW.value + 120)
        //当软键盘收起，在此处操作
        // _self.show_bo = true;
      }
    };
  }
  // ios：focusin和focusout支持冒泡，对应focus和blur, 使用focusin和focusout的原因是focusin和focusout可以冒泡，focus和blur不会冒泡，这样就可以使用事件代理，处理多个输入框存在的情况。
  if (isiOS) {
    document.body.addEventListener("focusin", () => {
      getViewPortW.value = String(+getViewPortW.value - 120)

      //软键盘弹出的事件处理
      //this.show_bo = false;
    });
    document.body.addEventListener("focusout", () => {
      getViewPortW.value = String(+getViewPortW.value + 120)

      //软键盘收起的事件处理
      //this.show_bo = true;
    });
  }
}

const { proxy } =  getCurrentInstance() as ComponentInternalInstance
const loading = ref(false);
const refreshing = ref(false);
const finished = ref(false);
const lipa = ()=>{
  inputText.value=inputText.value.replace(/\s*/g,'')

}
const  list1= ref([

])
const inputC = ()=>{
  if(!name.value){
    router.push({
      path: "/login",
      query: {
        mode: "",
      },
    });
  }
}
const showLiL = ref(false)
const showLiY = ref(false)
const getUserMuteTime = (e,a)=>{
  a.preventDefault();

  GetUserMuteTime({name:proxy.$name}).then(res=>{
    if(+res.data===1){showLiL.value = true}
    else if(+res.data===2){showLiY.value = true}
    else {chatroomSendText(e)}

  })
}
const router = useRouter()
onBeforeUnmount(()=>{
  if(NIM){
    NIM.disconnect()
    // this.initialization = true
    NIM = null
    var mo=function(e){e.preventDefault();};
    document.body.style.overflow='';//出现滚动条
    document.removeEventListener("touchmove",mo,false);
  }
})
const wayimgTongOpen = (item)=>{
  proxy.$showImagePreview(item)
  // showImagePreview({
  //   images:[item],
  //   startPosition:1,
  //   showIndex:false,
  //   // closeable: true,
  //
  // })
}

const mo = function(e){
  e.preventDefault();
};

const loadass = ref(false)
const handleScroll=(event)=> {


  const scrollTop = event.target.scrollTop; // 获取元素的滚动距离


  if (scrollTop === 0) {
    if(loadass.value){
      return
    }
    loadass.value = true
    getHistoryMsgsLiSh()

    console.log('Scrolled to the top!');


    // 在这里添加滚动到顶部时的操作


  }


}
const getHistoryMsgsDoneLish=(error, obj)=>{
  let zeroTimeTimestamp
  const now = new Date(); // 获取当前时间
  // now.setHours(0); // 将时间调整为零点
  // now.setMinutes(0);
  // now.setSeconds(0);
  // now.setMilliseconds(0);
  // zeroTimeTimestamp = now.getTime();
  zeroTimeTimestamp = now.getTime() - 12 * 60 * 60 * 1000;


  if(obj.msgs.length===100){
    loadass.value = false
  }
  let msgS = []
  for(let item of obj.msgs){
    if(item.custom) {
      item.custom =JSON.parse(item.custom)
    }

    if(+zeroTimeTimestamp<=item.time){
      msgS.push(item)
    }
  }

  console.log(obj)
  let tMess = []
  for(let item of msgS){
    // if(this.returnBIfgUid.indexOf(item.from)===-1){
    tMess.unshift(item)
    // }
  }
  // tMess.reverse()

  console.log(tMess)
  console.log('tMess')
  list1.value.unshift(...tMess)

  setTimeout(()=>{
    nextTick(()=>{
      let element = document.getElementById(listByOne.value.idClient)

      element.scrollIntoView();
    })
  },80)
  setTimeout(()=>{
    nextTick(()=>{
      let element = document.getElementById(listByOne.value.idClient)

      element.scrollIntoView();
    })
  },900)


  console.log(list1.value)

//   if(msgS.length===100){
//     // if(this.liveRoomMes<=200){
//     // this.getHistoryMsgsLiSh()
//     // }
//     // if(this.liveRoomMes.length>=500){
//     //   this.history = false
//     // }else{
//     //   this.history = true
//     // }
//   // }else{
//   //   this.history = false
//   // }
//   // this.$nextTick(()=>{
//   //   document.getElementById(this.idClient).scrollIntoView({behavior: "smooth"});
//   //
//   // })
//   // // this.$refs.liveChat.scrollIntoViewById(this.idClient)
//   // // let msgs = obj.msgs.reverse()
//   // // this.liveRoomMes = msgS
//   // this.$nextTick(() => {
//   //   if (this.$refs.liveChat) {
//   //     // this.$refs.liveChat.pagingSlout();
//   //   }
//   // })
}
const send=ref(false)

const getHistoryMsgsLiSh=()=>{
  // this.history = false
  // this.idClient = this.liveRoomMes[0].idClient

  listByOne.value = list1.value[0]
  NIM.getHistoryMsgs({
    timetag: list1.value[0].time,
    reverse:false,
    limit: 100,
    msgTypes: ['custom','image'],
    done: getHistoryMsgsDoneLish
  })
}
const listByOne = ref({})
const onmsgs = (e)=>{

  console.log('收到了消息',e)

  for(let item of e){
    if(item.type==="custom"){


      let flag = true

      // console.log(mes.chatroomId)
      // console.log('mes.chatroomId')
      // console.log(list1)
      list1.value.forEach(item1=>{

        if(item.idClient===item1.idClient){ // 对象里的唯一标识id
          // console.log(item.chatroomId)
          // console.log('item.chatroomId')
          // msg = '请勿重复添加！'
          flag = false;
        }
      })

      if(flag){
        item.custom = JSON.parse(item.custom)
        list1.value.push(item)
        nextTick(()=>{
          let element = document.getElementById(item.idClient)

          element.scrollIntoView();

        })
      }


      // liveChat
    }else if(item.type==='image'){
      item.custom = JSON.parse(item.custom)
      list1.value.push(item)
      nextTick(()=>{
        let element = document.getElementById(item.idClient)

        element.scrollIntoView();

      })

    }

    else if(item.type==='notification'){
      // if(item.attach.type==="memberEnter"){
      //   this.joinRoomName = item.attach.fromNick
      // }
    }else if(item.type==='tip'){
      // let tip = JSON.parse(item.tip)
      // if(tip.type==="A"){
      //   this.liveRoomMes = this.liveRoomMes.filter(it => it.idClient !== tip.data);
      // }
      // if(tip.type==="B"){
      //   this.returnBIfgUid.push(tip.data)
      //   this.liveRoomMes = this.liveRoomMes.filter(it => it.from !== tip.data);
      // }
      // if(tip.type==="C"){
      //   this.returnBIfgUid = this.returnBIfgUid.filter(it => it!==tip.data)
      //   this.getHistoryMsgs()
      // }
      // if(tip.type==="D"){
      //   if(+this.liveInfo.id===+tip.id){
      //     this.countdownTimeData = tip
      //
      //     this.countdownBool=true
      //     this.countdown()
      //   }
      //
      //
      //
      //   // this.getHistoryMsgs()
      // }
      // if(+tip.type===3){
      //   this.YXInitBYRoom()
      // }
    }

    // item.custom = JSON.parse(item.custom)
  }
}

const inputText = ref('')

const chatroomSendText=(e)=>{
  if(!e.replace(/\s*/g,'')){
    showFailToast('请输入内容')
    return
  }
  // if(send.value){
  //   showFailToast('5秒内只能发一次')
  //   return
  // }
  // send.value = true
  // setTimeout(()=>{
  //   send.value = false
  // },5000)
  console.log(proxy.$is_vip)
  console.log('proxy.$is_vip')
  let custom = JSON.stringify(
      // {userLevel:this.$jigouSDK.userInfo.job == '2'?'助理':this.$jigouSDK.userLevel.leve,color:userLevel:this.$jigouSDK.userInfo.job == '2'?'#fcb432':this.$jigouSDK.userLevel.color,Anchor:this.$jigouSDK.userInfo.job === '2'}
      {
        isVip:proxy.$is_vip,
        username:proxy.$name
      }
  )
  console.log(custom)
  NIM.sendCustomMsg({
    content: e,
    skipHistory:false,
    custom: custom,
    done: sendChatroomMsgDone
  });
}
const sendChatroomMsgDone = (error, msg)=> {
  console.log('发送聊天室定向消息' + msg.type + '消息' + (!error ? '成功' : '失败') + ', id=' + msg.idClient, error, msg);
  // send.value = false
  if(error){
    // getUserMuteTime()
  }
  // this.$refs.liveChat.inputNone()
  let mes = msg
  // mes.custom =JSON.stringify({userLevel:this.$jigouSDK.userLevel.leve,color:this.$jigouSDK.color,Anchor:false})
  // mes.custom ={userLevel:this.$jigouSDK.userInfo.job == '2'?'助理':this.$jigouSDK.userLevel.leve,color:this.$jigouSDK.userLevel.color,Anchor:this.$jigouSDK.userInfo.job === '2'}
  mes.custom = {
    isVip:proxy.$is_vip,
    username:proxy.$name
  }

  // {userLevel:this.$jigouSDK.userInfo.job == '2'?'助理':this.$jigouSDK.userLevel.leve,color:this.$jigouSDK.userInfo.job == '2'?'#fcb432':this.$jigouSDK.userLevel.color,Anchor:this.$jigouSDK.userInfo.job === '2'}

  if(!error){
    inputText.value = ''
    let flag = true
    list1.value.forEach(item=>{
      if(mes.idClient===item.idClient){ // 对象里的唯一标识id
        // msg = '请勿重复添加！'
        flag = false;
      }
    })
    if(flag){
      list1.value.push(mes)
      nextTick(()=>{
        let element = document.getElementById(mes.idClient)

        element.scrollIntoView();
      })

    }}


}

const  listQuery= ref({
  page: 1,
  limit: 10,
})
const onrefresh = ()=>{}



const getViewPortW = ref('')
const getViewPortWidth = ()=> {
  nextTick(()=>{
    if(document.documentElement.clientWidth){
      // document.getElementById("top-li").offsetHeight -
      return document.documentElement.clientWidth -  document.getElementById("top-lo").offsetHeight
    }else{
      return document.body.clientWidth - document.getElementById("top-lo").offsetHeight
      // - document.getElementById("top-li").offsetHeight
    }
  })



  //  || document.body.clientWidth;
}

const userWallet = ()=>{

  let pa = {
    user_id:localStorage.getItem("token")
  }
  if(!pa.user_id){
    proxy.$sayIs_vip(1)
    // userRecommendList()

    // return
  }else{
    UserWallet(pa).then(
        (res) => {
          if (+res.code === 200){
            proxy.$sayIs_vip(res.data.is_vip)
            // userRecommendList()
            createUser(res.data)


            // toLogin()
          }else{
            showFailToast(res.msg);

          }

        },
        err => {
          console.log(err);
          // showFailToast("请求有误");
        }
    );
  }
  console.log(pa)

}
const onconnect=(e)=>{

  console.log('初始化',e)
  // uni.setStorageSync('account',this.NIM.account)
  // this.Arrested = false
  // this.initialization = false
  // this.getHistoryMsgs()
}
let NIM = null
const getHistoryMsgs = ()=>{
  console.log(NIM)
  console.log(NIM.value)
  console.log('NIM.value')

  NIM.getHistoryMsgs({
    timetag: 0,
    reverse:false,
    limit: 100,
    msgTypes: ['custom','image'],
    done: getHistoryMsgsDone
  })
}
const getHistoryMsgsDone = (error, obj)=>{
  console.log('获取聊天室历史' + (!error?'成功':'失败'), error, obj.msgs);
  let zeroTimeTimestamp

  const now = new Date(); // 获取当前时间
  // now.setHours(0); // 将时间调整为零点
  // now.setMinutes(0);
  // now.setSeconds(0);
  // now.setMilliseconds(0);
  zeroTimeTimestamp = now.getTime() - 12 * 60 * 60 * 1000;

  let msgS = []

  for(let item of obj.msgs){
    // await this.wayreturnBIfgUid
    // this.returnBIfgUid
    if(item.custom){
      item.custom =JSON.parse(item.custom)
    }

    if(zeroTimeTimestamp<=item.time){

      msgS.push(item)
    }
    // item.custom = JSON.parse(item.custom)
  }
  let tMess = []
  for(let item of msgS){
    // if(this.returnBIfgUid.indexOf(item.from)===-1){
    tMess.push(item)
    // }
  }
  console.log(tMess)
  console.log('tMess')
  list1.value = tMess.reverse()
  nextTick(()=>{
    const listElement = document.getElementById('listType'); // 获取目标元素
    console.log(listElement)
    console.log('listElement')
    setTimeout(()=>{
      listElement.addEventListener('scroll', handleScroll); // 添加scroll事件监听器
      let element = document.getElementById(tMess[tMess.length-1].idClient)

      element.scrollIntoView();
    },200)

  })
  // let msgs = obj.msgs.reverse()
  // this.liveRoomMes = tMess.reverse()//!
  // this.$refs.liveChat.$forceUpdate();
  // this.$forceUpdate();
  // this.$nextTick(() => {
  //   if (this.$refs.liveChat) {
  //     setTimeout(()=>{
  //       document.getElementById('chatwelcome').scrollIntoView({behavior: "smooth"});
  //
  //       this.$refs.liveChat.pagingSlout();
  //     },600)
  //
  //   }
  // })
}

const name = ref('')
const createUser = (e)=>{
  console.log(e)
  let pa = {
    id:e.id,
    name:e.name,
  }
  name.value = e.name

  CreateUser(pa).then((res)=>{
    console.log(res)
    console.log(res.data.wy_token,res.data.wy_accid,e.name)
    console.log('res.data.wy_token,res.data.wy_accid,e.name')
    proxy.$sayIs_yx(res.data.wy_token,res.data.wy_accid,e.name)
    emptyUserName()


    console.log(res.data.wy_token)
    console.log('111111111111111')
    // disconnect
    NIM = initNIM({
      // token:uni.getStorageSync('accid'),
      // account:uni.getStorageSync('acctoken'),
      token: res.data.wy_token ,
      account:  res.data.wy_accid,
      chatroomId: 6103748300,
      chatroomAddresses: [
        "chatweblink01-sg.netease.im:443"
      ],
      ondisconnect:()=>{
        if(disconnect.value){
          disconnect.value = false
          init()
        }

      },
      onmsgs:onmsgs,
      onconnect: (e)=>{


        console.log(e)
        console.log('onconnect')
        getHistoryMsgs()
      },

    })

  },err=>{})


  // CreateUser
}
const init = async () => {

  console.log(proxy.$name)
  console.log('proxy.$name')

  if((!!proxy.$wy_accid&&!!proxy.$wy_token&&!!proxy.$name)&&(proxy.$wy_accid!=='undefined'&&proxy.$wy_token!=='undefined'&&proxy.$name!=='undefined')){
    console.log()
    NIM = initNIM({
      // token:uni.getStorageSync('accid'),
      // account:uni.getStorageSync('acctoken'),
      token: proxy.$wy_token ,
      account:  proxy.$wy_accid,
      chatroomId: 6103748300,
      chatroomAddresses: [
        "chatweblink01-sg.netease.im:443"
      ],
      onmsgs:onmsgs,
      ondisconnect:()=>{
        if(disconnect.value){
          disconnect.value = false
          init()
        }

      },
      onconnect: (e)=>{


        console.log(e)
        console.log('onconnect')
        getHistoryMsgs()
      },

    })


  }else {
    await userWallet()
  }
  await showNotice()

  await nextTick(() => {
    document.body.style.overflow = 'hidden';
    document.addEventListener("touchmove", mo, false);
    if (document.documentElement.clientWidth) {
      getViewPortW.value = String(
          (document.documentElement.clientHeight
              // - document.getElementById("top-li").offsetHeight)
              - document.getElementById("top-lo").offsetHeight)
          -68)
      console.log(getViewPortW.value)
    } else {
      getViewPortW.value = String(
          (document.body.clientHeight
              - document.getElementById("top-lo").offsetHeight)
          // - document.getElementById("top-li").offsetHeight)
          -68
      )
    }
  })
}
const count = ref([])
const finish = ref([])
const no_finish = ref([])
const link = ref('')
onMounted(() => {
  if(proxy.$wy_accid&&proxy.$wy_accid!=='undefined'){
    emptyUserName()
  }
  if(!proxy.$token){
    router.push({
      path: "/index",
      query: {
        mode: "",
      },
    });
  }



  init()
  // getViewPortW.value = (getViewPortWidth() + 'px')
  // monitorKeyboard()


})
const userRecommendList = async () => {
  let pa = {
    is_vip:proxy.$is_vip
    // is_vip:2
  }
  const res = await UserRecommendList(pa)
  if (+res.code === 200) {
    finish.value = res.data.finish
    no_finish.value = res.data.no_finish
    // count.value = res.data.content
    // link.value =  res.data.link
  }
}
const  openUrl = ()=>{
  window.open(link.value)
}
const toChatRoom = ()=>{
  router.push({
    path: "/index",
    query: {
      mode: "",
    },
  });
}
const vlaueHead = ref('')
const banner = ref('')
const showNotice = async () => {
  const res = await ShowNotice();
  if (+res.code === 200) {
    // count.value = res.data.includes('\n') ? res.data.content.split('\n') : res.data.content
    count.value =res.data[0].content.split('\n')
    vlaueHead.value = res.data[1].content

    link.value =  res.data.link
    banner.value = res.data.banner
    await nextTick(() => {
      setTimeout(()=>{
        if (document.documentElement.clientWidth) {
          getViewPortW.value = String(
              (document.documentElement.clientHeight
                  // - document.getElementById("top-li").offsetHeight)
                  - document.getElementById("top-lo").offsetHeight)
              - 68)
          console.log(getViewPortW.value)
        } else {
          getViewPortW.value = String(
              (document.body.clientHeight
                  - document.getElementById("top-lo").offsetHeight)
              // - document.getElementById("top-li").offsetHeight)
              - 68
          )
        }
      },800)
    })
  }
  // console.log(res)
}


// const showNotice = async () => {
//   await ShowNotice().then(res => {
//     debugger
//     if (+res.code === 200) {
//       count.value = res.data.content
//       console.log(res)
//     }
//   }, err => {
//     console.log(err);
//     showFailToast("请求有误");
//   })
// }
const list = ref<object>({li:11})
// const

</script>

<style scoped lang="less">
.imgVipzhen{
  font-size: 9px;
  // padding: 2px 7px;
  border-radius: 2px;
  text-align: center;
  width: 30px;
  height: 13px;
  line-height: 14px;
  display: inline-block;
  margin-top: 1px;
}
.imgVipzhenImg{
  // border-radius: 2px;
  width: 22px;
  height: 12px;
  display: inline-block;
  vertical-align: middle;
  margin-top: 1.5px;
}
.imgTong{
  max-width: 60px;
  max-height: 70px;
}
::v-deep .van-field{
  background-color: #3E3E3E;
}
::v-deep .van-field__control{
  color: #fff;

}
.send-chat{
  padding: 10px 10px;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  position: fixed;
  bottom: 0;
  // left: 0;
  background-color: #282828;
  // height: 60px;
}
.line-lt{
  position: absolute;
  bottom: 8px;
  width: 30px;
  height: 3px;
  background-color: #48D9AA;
  border-radius: 2px;
}
.count_chat_box{
  background-color: #373737;
  position: relative;
}
.count{
  background-color: #282828;
  .login-box_but_list{
    padding: 0 10px;
    display: flex;
    justify-content: space-between;
    div{
      width: 100%;
      text-align: center;
      color: #fff;
    }
  }
  .count_count{
    margin-top: 10px;
    padding: 0 12px;
    >div{
      //padding: 0 12px;
      //padding: 0 40px;
      color: #fff;
      text-align: left;
      font-size: 14px;
      line-height: 26px;
      font-weight: bold;
    }
  }
  .login-box_li{
    padding-left: 12px;
    //background-color: #282828;
    color: #7FDCAB;
    display: flex;
    justify-content: left;
    align-items: center;
    margin: 16px 0 0 0;
    font-weight: bold;
    font-size: 1rem;
  }
  .login-box_list{
    padding: 0px 8px 8px 8px;
  }

}
.chat_wapper{
  height: 100%;
  position: relative;
  //background-color: #f6f6f6;
}
::v-deep .van-field{

}
::v-deep .van-notice-bar{
  padding:0 13px;
  height: 30px;
}
::v-deep .van-notice-bar .van-image{
  margin-left: 1px;
}
::v-deep .van-notice-bar__wrap{
  padding-left: 10px;
  margin-left: 10px;
}
::v-deep .van-notice-bar__content{
}
::v-deep .emit_name input::placeholder{
  color: #747474;
}
::v-deep .emit_name input{
  color: #000;
}
::v-deep .calToa{
  background-color: #E4E4E4!important;

}
::v-deep .calToa  .van-toast__text{
  background-color: #E4E4E4!important;

}
</style>
